#/bin/python
#coding:utf8
'''
Created on 2011-5-7

@author: mark
'''

import config

db = config.database
mc = config.memcache_client

def getTypes():
    types = db.select('type')
    return types

def getTypeProblemCount(tid):
    key = str('tcount_%s' % tid)
    count = mc.get(key)
    if not count:
        count = _getTypeProblemCount(tid)
        if count:
            mc.set(key, count, config.pagecountCacheTimeout)
    return count
        
def _getTypeProblemCount(tid):
    results = db.query("SELECT COUNT(*) as count FROM problem WHERE type=$tid", vars={"tid":tid})
    return results[0]['count']


def getAllProblemCount():
    key = str("AllProblemCount")
    count = mc.get(key)
    if not count:
        count = _getAllProblemCount()
        if count:
            mc.set(key, count, config.pagecountCacheTimeout)
    return count

def _getAllProblemCount():
    results = db.query("select count(*) as count from problem")
    return results[0]['count']
 
def getMyProblemCount(uid):
    key = str('mypcount_%s' % uid)
    count = mc.get(key)
    if not count:
        count = _getMyProblemCount(uid)
        if count:
            mc.set(key, count, config.pagecountCacheTimeout)
    return count

def _getMyProblemCount(uid):
    results = db.query("SELECT COUNT(*) as count FROM problem WHERE asker=$uid", vars={"uid":uid})
    return results[0]['count']


def getType(tid):
    key = str("type_%s" % tid)
    type = mc.get(key)
    if not type:
        type = _getType(tid)
        if type :
            mc.set(key, type, config.cache_timeout)
    return type

def _getType(tid):
    results = db.select("type", where="tid=%s" % tid)
    if results:
        return results[0]

